from abc import ABC, abstractmethod


class State(ABC):
    @abstractmethod
    def on_event(self, event):
        pass

    @abstractmethod
    def on_enter(self):
        pass

    @abstractmethod
    def on_exit(self):
        pass


class StartState(State):
    def on_event(self, event):
        if event == "start":
            return RunningState()
        return self

    def on_enter(self):
        print("11 进入启动模式")

    def on_exit(self):
        print("12 退出启动模式")


class RunningState(State):
    def on_event(self, event):
        if event == "pause":
            return PauseState()
        elif event == "stop":
            return StopState()
        return self

    def on_enter(self):
        print("21 进入运行模式")

    def on_exit(self):
        print("22 退出运行模式")


class PauseState(State):
    def on_event(self, event):
        if event == "resume":
            return RunningState()
        elif event == "stop":
            return StopState()
        return self

    def on_enter(self):
        print("31 进入暂停模式")

    def on_exit(self):
        print("32 退出暂停模式")


class StopState(State):
    def on_event(self, event):
        if event == "restart":
            return RunningState()
        return self

    def on_enter(self):
        print("41 进入停止模式")

    def on_exit(self):
        print("42 退出停止模式")


# 状态机
class StateMachine:
    def __init__(self):
        self.cur_state = StartState()
        self.cur_state.on_enter()

    def trigger(self, event):
        # 退出当前状态
        self.cur_state.on_exit()
        # 切换状态
        self.cur_state = self.cur_state.on_event(event)
        # 进入新状态
        self.cur_state.on_enter()


# 使用状态机
if __name__ == "__main__":
    sm = StateMachine()
    sm.trigger("start")
    sm.trigger("pause")
    sm.trigger("resume")
    sm.trigger("stop")
    sm.trigger("restart")
